﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using yoyo;
using UnityEngine.Experimental.Networking;
using XLua;
using System.IO;

public class ResUpdate : MonoBehaviour
{

    /// <summary>
    /// 需要下载文件目录
    /// </summary>
    private List<string> NeedDownFiles;

    /// <summary>
    /// 本地MD5目录
    /// </summary>
    private Dictionary<string, string> LocalResVersion;

    /// <summary>
    /// 服务器MD5目录
    /// </summary>
    private Dictionary<string, string> ServerResVersion;

    private LuaEnv luaenv = new LuaEnv();

    void Start()
    {
        LocalResVersion = new Dictionary<string, string>();
        ServerResVersion = new Dictionary<string, string>();
        NeedDownFiles = new List<string>();
        //如果本地目录不存在Version
        if (!IO.IsExists(GlobalFile.UnityPath + GlobalFile.VERSION_FILE))
        {
            //直接从服务器下
            Res.ReadText(GlobalFile.strpath + GlobalFile.VERSION_FILE, (text) =>
            {
                string netversion = text;
                //关联服务器version 和 dictionary
                ParseVersionFile(netversion, ServerResVersion);
                //对比本地容器和服务器容器
                CompareVersion();
                //下载更新
                DownLoadRes();
            }, ResLoadType.Path);
        }
        else
        {
            //获取本地version
            Res.ReadText(GlobalFile.UnityPath + GlobalFile.VERSION_FILE, (text) =>
            {
                string localversion = text;
                //关联本地version 和 dictionary
                ParseVersionFile(localversion, LocalResVersion);
            }, ResLoadType.Path);

            //获取服务器列表
            Res.ReadText(GlobalFile.strpath + GlobalFile.VERSION_FILE, (text) =>
            {
                string netversion = text;
                //关联服务器version 和 dictionary
                ParseVersionFile(netversion, ServerResVersion);
                //对比本地容器和服务器容器
                CompareVersion();
                //下载更新
                DownLoadRes();

            }, ResLoadType.Path);
        }



    }


    private void XLuaFix()
    {
        //TODO：热更新补丁
        luaenv.AddLoader((ref string filename) =>
        {
            string path = Application.persistentDataPath + "/" + filename;
            if (File.Exists(path))
            {
                return File.ReadAllBytes(path);
            }
            else
                return null;
        });
        luaenv.DoString(@"require 'myHotfix.lua.txt'");
    }

    private void ParseVersionFile(string content, Dictionary<string, string> dict)
    {
        if (content == null || content.Length == 0)
        {
            return;
        }
        string[] items = content.Split(new char[] { '\n' });
        foreach (string item in items)
        {
            string[] info = item.Split(new char[] { ',' });
            if (info != null && info.Length == 2)
            {
                dict.Add(info[0], info[1]);
            }
        }
    }

    private void CompareVersion()
    {
        foreach (var version in ServerResVersion)
        {
            string fileName = version.Key;
            string serverMd5 = version.Value;
            //新增的资源
            if (!LocalResVersion.ContainsKey(fileName))
            {
                NeedDownFiles.Add(fileName);
            }
            else
            {
                //需要替换的资源  
                string localMd5;
                LocalResVersion.TryGetValue(fileName, out localMd5);
                if (!serverMd5.Equals(localMd5))
                {
                    NeedDownFiles.Add(fileName);
                }
            }
        }
    }


    //依次加载需要更新的资源  
    private void DownLoadRes()
    {
        if (NeedDownFiles.Count == 0)
        {
            IO.UpdateLocalVersionFile(ServerResVersion);
            XLuaFix();
            return;
        }
        string file = NeedDownFiles[0];
        NeedDownFiles.RemoveAt(0);

        //下载新资源 如果本地存在则先删掉然后更新文件
        NetInstrument.Get(GlobalFile.strpath + file, (www) =>
        {
            IO.ReplaceLocalRes(GlobalFile.UnityPath + file, www.downloadHandler.data);
            DownLoadRes();
        });
    }
}
